import store from '@/store'

export function hasPermission(roles, permissionRoles){
  if(roles.includes('admin')) return true // admin permission passed directly
  if(!permissionRoles) return true
  return roles.some(role => permissionRoles.includes(role))
}

export default function checkPermission(value){
  if(value && value instanceof Array && value.length > 0) {
    const roles = store.getters && store.getters.roles
    return roles.some(role => value.includes(role))
  } else {
    console.error(`need roles! Like v-permission="['admin','editor']"`)
    return false
  }
}

export function hasMetaPermission(roles, route){
  if(route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  }
  return true
}

export function filterAsyncRouter(asyncRouterMap, roles){
  return asyncRouterMap.filter(route => {
    if(hasMetaPermission(roles, route)) {
      if(route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
}
